package com.a51integrated.sfs2x;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;

import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.variables.*;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import com.smartfoxserver.v2.extensions.ExtensionLogLevel;

public class GetHighscoreRequestHandler extends BaseClientRequestHandler {

	@Override
	public void handleClientRequest(User player, ISFSObject params) {
		// TODO Auto-generated method stub

		// The user highscores are tracked by the the time a user spends on obtaining the maximum amount of points.
		// If a user is able to achieve a better time (i.e. obtain the maximum amoun of points in less time than he or she did previously),
		// this is stored and maintained in the database.

		// Get the database manager.
		IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
		
		// Create a connection object.
		Connection connection;
		try
		{
			// Grab a connection from the DB mananger.
			connection = dbManager.getConnection();			

			String username = player.getName();

			PreparedStatement stmt = connection.prepareStatement("SELECT `highscore` FROM `highscores` WHERE `username`='" + username + "'");
			ResultSet resSet = stmt.executeQuery();

			SFSObject rtn = new SFSObject();
			if (!resSet.first())
			{
				// The result set is empty, return a score of 0.
				rtn.putInt("time", 0);
				rtn.putBool("scorefound", false);
			}
			else
			{
				// An entry was found.
				rtn.putInt("time", resSet.getInt("highscore"));
				rtn.putBool("scorefound", true);				
			}
			getParentExtension().send("gethighscore", rtn, player);
			
			connection.close();
		}
		catch(SQLException e)
		{
			trace(ExtensionLogLevel.WARN, "SQL Failed: " + e.toString());
		}
	}

}
